import { forEach, once } from '@/modules/util'

class RouterMiddleware {
  constructor(middlewares) {
    this.middlewares = middlewares
  }

  /**
   * 可以挂载中间件到全局路由守卫上
   *
   * @param {Object} {to, from, next}
   * @memberof RouterMiddleware
   */
  use({ to, from, next }) {
    next = once(next, this)
    forEach(to.meta, (value, key) => {
      forEach(this.middlewares, (middleware, middlewareName)=>{
        if (middlewareName === key) {
          middleware.call(this, { to, from, next }, value)
        }
      })
    })
    next()
  }
}

export default RouterMiddleware
